﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace Com.AAS.Common.Utils
{
    public class GZIPUtil
    {
        /// <summary>
        /// GZIP压缩
        /// </summary>
        /// <param name="inBytes"> 需要压缩的byte[]</param>
        /// <returns>压缩后的数据结果,返回结果为byte[]</returns>
        public static byte[] DoZIPToBytes(byte[] inBytes)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                GZipStream zipStream = new GZipStream(memory, CompressionMode.Compress, true);
                zipStream.Write(inBytes, 0, inBytes.Length);
                zipStream.Close();
                return memory.ToArray();
            }
        }

        /// <summary>
        /// GZIP压缩
        /// </summary>
        /// <param name="inBytes"> 需要压缩的byte数组</param>
        /// <returns>压缩后的数据结果,返回结果为String</returns>
        public static String DoZIPToString(byte[] inBytes)
        {
            UTF8Encoding ascill = new UTF8Encoding();
            String outString = ascill.GetString(DoZIPToBytes(inBytes));
            return outString;
        }

        /// <summary>
        /// UNZIP压缩
        /// </summary>
        /// <param name="inBytes"> 需要压缩的byte[]</param>
        /// <returns>压缩后的数据结果,返回结果为byte[]</returns>
        public static byte[] DoUNZIPToBytes(byte[] inBytes)
        {
            using (MemoryStream memory = new MemoryStream(inBytes))
            {
                GZipStream zipStream = new GZipStream(memory, CompressionMode.Decompress);
                MemoryStream outBuffer = new MemoryStream();
                byte[] block = new byte[1024];
                while (true)
                {
                    int bytesRead = zipStream.Read(block, 0, block.Length);
                    if (bytesRead <= 0)
                        break;
                    else
                        outBuffer.Write(block, 0, bytesRead);
                }
                zipStream.Close();
                return memory.ToArray();
            }
        }

        /// <summary>
        /// UNZIP压缩
        /// </summary>
        /// <param name="inBytes"> 需要压缩的byte数组</param>
        /// <returns>压缩后的数据结果,返回结果为String</returns>
        public static byte[] DoUNZIPToString(String inString)
        {
            UTF8Encoding ascill = new System.Text.UTF8Encoding();
            return DoUNZIPToBytes(ascill.GetBytes(inString));
        }
    }
}
